/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jpa.controller;

import general.util.StringUtil;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import jpa.controller.exceptions.NonexistentEntityException;
import jpa.entity.Empresa;

/**
 *
 * @author isaias
 */
public class EmpresaJpaController {

    public EmpresaJpaController() {
        emf = Persistence.createEntityManagerFactory("ProjectObraPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Empresa empresa) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(empresa);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Empresa empresa) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            empresa = em.merge(empresa);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = empresa.getId();
                if (findEmpresa(id) == null) {
                    throw new NonexistentEntityException("The empresa with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Empresa empresa;
            try {
                empresa = em.getReference(Empresa.class, id);
                empresa.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The empresa with id " + id + " no longer exists.", enfe);
            }
            em.remove(empresa);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    
    public List<Empresa> findEmpresaEntitiesByName(String filterName) {
        String sql = "SELECT e FROM Empresa e";

        if (!StringUtil.isNullOrEmpty(filterName)) {

            sql += " WHERE e.name LIKE :name ";
        }

        sql += " ORDER BY e.name";

        EntityManager em = getEntityManager();

        try {
            Query query = em.createQuery(sql);

            if (!StringUtil.isNullOrEmpty(filterName)) {
                query.setParameter("name", "%" + filterName.toUpperCase() + "%");
            }

            return query.getResultList();
        } catch (Exception ex) {
            ex.printStackTrace();
            return new ArrayList<Empresa>();
        } finally {
            em.close();
        }
    }
    
    public Empresa findEmpresaForName(String name) {
        String sql = "SELECT e FROM Empresa e WHERE e.name LIKE :name";

        EntityManager em = getEntityManager();

        try {
            return (Empresa) em.createQuery(sql).setParameter("name", name.toUpperCase()).setMaxResults(1).getSingleResult();
        } catch (Exception ex) {
            if (!(ex instanceof NoResultException)) {
                ex.printStackTrace();
            }
            return null;
        } finally {
            em.close();
        }
    }

    public List<Empresa> findEmpresaAjaxName(String nameFilter, int max_results) {
        String sql = "SELECT e FROM Empresa e WHERE e.name LIKE :name";

        Query query = getEntityManager().createQuery(sql);

        query.setParameter("name", "%" + nameFilter.toUpperCase() + "%");

        query.setMaxResults(max_results);

        try {
            return query.getResultList();
        } catch (Exception ex) {
            ex.printStackTrace();
            return new ArrayList<Empresa>();
        }
    }

    public List<Empresa> findEmpresaEntities() {
        return findEmpresaEntities(true, -1, -1);
    }

    public List<Empresa> findEmpresaEntities(int maxResults, int firstResult) {
        return findEmpresaEntities(false, maxResults, firstResult);
    }

    private List<Empresa> findEmpresaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Empresa.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Empresa findEmpresa(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Empresa.class, id);
        } finally {
            em.close();
        }
    }

    public int getEmpresaCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Empresa> rt = cq.from(Empresa.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
